//
//  QDHDHZWebViewController.swift
//  QDMetroClient
//
//  Created by YueWen on 2019/4/18.
//  Copyright © 2019 YueWen. All rights reserved.
//

import UIKit


/// 活动盒子的webView
final class QDHDHZWebViewController: RITLWebViewController {

    /// 是否存在导航控制器
    private var hasParentNavigationController: Bool {
        return parent is UINavigationController
    }
    
    /// 返回图片
    private var backIndicatorImage: UIImage? {
        return "nav_back_default".namedImage?.ritl_renderOrigin
    }
    
    /// 是否自动加载
    override func autoRequestUrlAtViewDidLoad() -> Bool {
        return false
    }
    
    /// 交互name
    override var messageHanderNames: [String]? {
        return ["hzShare"]
    }
    
    /// 分享的信息
    private var shareMessage:(title: String,content: String,imgUrl: String,url: String) = ("","","","")
    
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        view.backgroundColor = .white
        progressView.tintColor = QDColors.theme
        
        if hasParentNavigationController {
            
            // 设置backItem
            let barButtonItem = UIBarButtonItem(title: "", style: .done, target: nil, action: nil)
            navigationItem.backBarButtonItem = barButtonItem
            
            // 设置back
            navigationController?.navigationBar.backIndicatorImage = backIndicatorImage
            navigationController?.navigationBar.backIndicatorTransitionMaskImage = backIndicatorImage
            setDefaultNavigationBarWhenHasParentNavigationController()
        }
        
        requestUrl()
    }

    
    // 对系统进行适配
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        
        let barHeight = BarDistance.NavigationBar.height
        let version = (UIDevice.current.systemVersion as NSString).floatValue
        
        if version > 11.0 { /// 如果系统大于11
            webView.ritl_originY = barHeight
            webView.ritl_height = view.ritl_height - barHeight
        }else {
            // 获得webView应该的高度
            let height = CGFloat(UIScreen.main.ritl_height - barHeight)
            guard height != webView.ritl_height else { return }
            webView.ritl_height = height
        }
    }
    
    
    deinit {
        WKWebsiteDataStore.default().removeData(ofTypes: WKWebsiteDataStore.allWebsiteDataTypes(), modifiedSince: Date(timeIntervalSince1970: 0)) {}
        print("QDHDHZWebViewController is deinit")
    }
    
    
    override func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        super.webView(webView, didFinish: navigation)
        if autoTitle && navigationItem.title == "加载中..." {
            navigationItem.title = "活动"
        }
    }
}


extension QDHDHZWebViewController: WKScriptMessageHandler {
    
    func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
        
        /// 获得分享的信息
        func getShareMessage(messageBody: [String: String]) {
            
            //获得分享内容
            shareMessage = (messageBody["title"] ?? "",messageBody["content"] ?? "",messageBody["imgUrl"] ?? "",messageBody["linkUrl"] ?? "")
            
            //如果分享链接以及title不为空，展示分享按钮
            guard !shareMessage.title.isEmpty && !shareMessage.url.isEmpty else { return }
            
            navigationItem.title = shareMessage.title.limit(7)
            
            //显示分享按钮
            navigationItem.rightBarButtonItem = UIBarButtonItem(image: "share_gray".namedImage, style: .done, target: self, action: #selector(doShare))
        }
        
        //获得body
        guard let messageBody = message.body as? [String: Any] else { return }
        
        print("messageBody = \(messageBody)")
        //如果获得分享文件
        if let shareConfig = messageBody["shareConfig"] as? [String: String] {
            getShareMessage(messageBody: shareConfig); return
        }
        
        //如果是唤起分享
        if let event = messageBody["event"] as? String, event == "doShare" {
            doShare()
        }
    }
    
    
    /// 进行分享
    @objc func doShare(){
        
        guard let deepLinkUrl = HeziSDKManager.sharedInstance()?.buildDeepLink(withUrl: shareMessage.url, scheme: "qdmetro://", customeParams: [AnyHashable : Any]()) else { return }
        
        QDShareManager.share(url: deepLinkUrl, imageUrl: shareMessage.imgUrl, title: shareMessage.title, desc: shareMessage.content, from: self)
    }
}
